package com.baizhi.cmfz.realm;

import com.baizhi.cmfz.dao.AdminDao;
import com.baizhi.cmfz.entity.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义认证器类，继承AuthenticatingRealm类
 *
 * @author zhanglh
 * @date 2019/09/25
 */
public class AuthenRealm extends AuthenticatingRealm {
    @Autowired
    private AdminDao adminDao;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取token中的数据
        UsernamePasswordToken token1 = (UsernamePasswordToken) token;
        String username = token1.getUsername();
        //根据获取到的用户名查询数据库
        Admin admin = adminDao.login(username);
        //查询结果不为null
        if (admin != null) {
            //封装info
            //参数1：查询到的用户名，参数2：查询到的凭证，参数3：当前类名
            SecurityUtils.getSubject().getSession().setAttribute("admin", admin);
            return new SimpleAuthenticationInfo(admin.getUsername(), admin.getPassword(), this.getName());
        }
        //没有查到结果，返回null
        return null;
    }
}
